<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel"
      >
        <template slot="menuLeft">
          <el-button
            v-if="permissions.workorder_workordercps_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel">导出
          </el-button>
        </template>
        <!--        <template slot-scope="{row,index}" slot="workOrderInfo">
                  <el-table :data="row.workOrderInfo ? JSON.parse(row.workOrderInfo) : []"  v-if="row.workOrderInfo"  border style="width: 100%;display: inline-block">
                    <el-table-column prop="workshopName" label="车间" show-overflow-tooltip align="center" ></el-table-column>
                    <el-table-column prop="productionLineName" label="产线" show-overflow-tooltip align="center" ></el-table-column>
                    <el-table-column width="70px" prop="scheduleNum" label="排产数量" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="capacity" label="标准产量" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="startDate" label="开工时间" show-overflow-tooltip align="center" ></el-table-column>
                    <el-table-column prop="dailyCompleteQty" label="日完成量" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="completeTime" label="完成时间" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="remainingQty" label="剩余数量" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="completeQty" label="已完成量" show-overflow-tooltip align="center"></el-table-column>
                    <el-table-column prop="moStatus" label="状态" show-overflow-tooltip align="center" >
                      <template slot-scope="scope">
                          <span :class="getStatusClass(scope.row.moStatus)">
                            {{ scope.row.moStatus }}
                          </span>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-else description="暂无排产" style="height: 50px" :image-size="30"></el-empty>
                </template>-->
        <!--出货时间表单自定义-->
        <template slot="deliveryDateForm" slot-scope="{ row }">
          <el-date-picker
            v-model="deliveryDate"
            type="date"
            @change="deliveryDateChange(row)"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            placeholder="请选择出货时间"
          >
          </el-date-picker>
        </template>
        <!--入库时间显示自定义-->
        <template slot="storeDate" slot-scope="{ row }">
          {{ row.storeDate }}
        </template>
        <!--        <template slot-scope="{row,index}" slot="menu">
        &lt;!&ndash;          <el-button type="text" size="small"  :disabled="row.moStatus==='已完成' "
                    :icon="row.$cellEdit?'el-icon-circle-plus-outline':'el-icon-share'"
                    @click="rowCell(row,index)"
                  >{{row.$cellEdit?'保存':'分配产线'}}</el-button>
                  <el-button v-if="row.$cellEdit"  type="text" icon="el-icon-circle-close" size="small" @click="$refs.crud.rowCancel(row,index)">取消</el-button>&ndash;&gt;
                  &lt;!&ndash;      <el-button type="text"  icon="el-icon-s-order"  size="small"   :disabled="row.moStatus!='已完工'" @click="supplementaryOrder(row,index)">补单</el-button>&ndash;&gt;

                  <el-button type="text" size="small" :icon="row.$cellEdit?null:'el-icon-edit'" @click="$refs.crud.rowCell(row, index)">
                    {{row.$cellEdit?'保存':'编辑'}}
                  </el-button>
                  <el-button v-if="row.$cellEdit" type="text"  size="small" @click="$refs.crud.rowCancel(row,index)">
                    取消
                  </el-button>
                  <el-button type="text"  icon="el-icon-tickets"  size="small"   @click="openScheduling(row,index)">排产</el-button>
                  <el-button type="text"  icon="el-icon-tickets"  size="small"   @click="workOrderBomDetails(row,index)">工单物料</el-button>
                  <el-button type="text"  icon="el-icon-document"  size="small"   @click="workOrderReportDetails(row,index)">报工详情</el-button>
                  <el-button type="text"  icon="el-icon-document" size="small" @click="zzpReportDetails(row,index)">在制品报废明细</el-button>
                  <el-button type="text"  icon="el-icon-document" size="small" @click="wlReportDetails(row,index)">物料报废明细</el-button>
                  <el-button type="text"  icon="el-icon-document" size="small" @click="reworkReportDetails(row,index)">返工原因明细</el-button>
                  <el-button type="text"  icon="el-icon-delete"  size="small"   :disabled="row.moStatus!='未生产'" @click="handleDel(row,index)">删除</el-button>
                </template>-->
        <!--自定义操作栏合并菜单-->
        <template slot="menu" slot-scope="scope">
<!--          <el-button
            type="text"
            icon="el-icon-tickets"
            size="small"
            plain
            @click="workOrderPlan(scope.row, scope.index)"
            >排产规划</el-button
          >-->
          <el-button
            v-if="scope.row.$cellEdit"
            type="text"
            size="small"
            plain
            @click="$refs.crud.rowCancel(scope.row, scope.index)"
            >取消</el-button
          >
          <el-button
            v-if="scope.row.$cellEdit"
            type="text"
            size="small"
            plain
            @click="
              handleUpdate(
                scope.row,
                () => {},
                () => {}
              )
            "
            >保存</el-button
          >
          <el-button
            v-else
            type="text"
            icon="el-icon-edit"
            size="small"
            plain
            @click="
              deliveryDate = scope.row.deliveryDate;
              $refs.crud.rowCell(scope.row, scope.index);
            "
            >编辑</el-button
          >

          <el-button
            type="text"
            icon="el-icon-tickets"
            size="small"
            plain
            @click="workOrderDetails(scope.row, scope.index)"
            >详情追溯</el-button
          >
        </template>
        <template slot="scheduleStatus" slot-scope="{ row }">
          <div>
            <div v-if="row.scheduleStatus == 0">
              <b style="color:orange">待排产</b>
            </div>
            <div v-else>
              <b style="color:green">已排产</b>
            </div>
          </div>
        </template>

        <template slot-scope="{ row, index }" slot="menuBtn">
          <el-dropdown-item
            v-if="row.$cellEdit"
            type="text"
            size="small"
            style="display: flex; justify-content: space-between"
          >
            <span @click="$refs.crud.rowCancel(row, index)">取消</span>
            <span
              @click="
                handleUpdate(
                  row,
                  () => {},
                  () => {}
                )
              "
              >保存</span
            >
          </el-dropdown-item>
          <el-dropdown-item
            v-else
            type="text"
            size="small"
            :icon="'el-icon-edit'"
            @click.native="
              deliveryDate = row.deliveryDate;
              $refs.crud.rowCell(row, index);
            "
          >
            编辑
          </el-dropdown-item>
          <!--          <el-dropdown-item divided icon="el-icon-tickets"  size="small"   @click.native="openScheduling(row,index)">排产</el-dropdown-item >-->
          <el-dropdown-item
            divided
            icon="el-icon-tickets"
            size="small"
            @click.native="workOrderDetails(row, index)"
            >详情
          </el-dropdown-item>
        </template>
      </avue-crud>

      <!--BOM详情目录弹窗页面-->
      <el-dialog
        title=""
        :visible.sync="bomDialogVisible"
        width="50%"
        lock-scroll
        v-if="bomDialogVisible"
        :fullscreen="bomDialogFull"
      >
        <el-backtop
          target=".el-card__body .el-dialog__wrapper .el-dialog"
          :right="15"
          :bottom="20"
          :visibility-height="1"
        />
        <el-backtop :bottom="60"></el-backtop>
        <template slot="title">
          <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
              <span
                style="
                  display: inline-block;
                  background-color: #3478f5;
                  width: 3px;
                  height: 20px;
                  margin-right: 5px;
                  float: left;
                  margin-top: 2px;
                "
              ></span>
              物料详情<i
                class="el-breadcrumb__separator el-icon-arrow-right"
              ></i
              >工单：{{ docNo }}——品号：{{ itemCode }}
            </span>
          </div>
        </template>
        <!--BOM详情页面-->
        <bomDetailsPage ref="workOrderBomRef" :docNo="docNo" />
      </el-dialog>

      <!--报工详情目录弹窗页面-->
      <el-dialog
        title=""
        :visible.sync="reportDialogVisible"
        width="50%"
        lock-scroll
        v-if="reportDialogVisible"
        :fullscreen="reportDialogFull"
      >
        <el-backtop
          target=".el-card__body .el-dialog__wrapper .el-dialog"
          :right="15"
          :bottom="20"
          :visibility-height="1"
        />
        <el-backtop :bottom="60"></el-backtop>
        <template slot="title">
          <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
              <span
                style="
                  display: inline-block;
                  background-color: #3478f5;
                  width: 3px;
                  height: 20px;
                  margin-right: 5px;
                  float: left;
                  margin-top: 2px;
                "
              ></span>
              {{ title
              }}<i class="el-breadcrumb__separator el-icon-arrow-right"></i
              >工单：{{ docNo }}——品号：{{ itemCode }}
            </span>
          </div>
        </template>
        <!--报工详情页面-->
        <workOrderReportDetailsPage
          v-if="flg === 'gd'"
          ref="reportRef"
          :docNo="docNo"
        />
        <dr8Page v-if="flg === 'dr8'" ref="dr8Ref" :viewDocNo="docNo" />
        <genPage v-if="flg === 'gen'" ref="genRef" :viewDocNo="docNo" />
        <sr8Page v-if="flg === 'sr8'" ref="sr8Ref" :viewDocNo="docNo" />

        <!--        &lt;!&ndash;在制品详情页面&ndash;&gt;
                <zzpReportDetailsPage v-if="flg==='zzp'" ref="zzpReportRef" :docNo="docNo"/>
                &lt;!&ndash;物料报废详情页面&ndash;&gt;
                <wlReportDetailsPage v-if="flg==='wl'" ref="wlReportRef" :docNo="docNo"/>
                &lt;!&ndash;返工原因详情页面&ndash;&gt;
                <reworkReportDetailsPage v-if="flg==='rework'" ref="reworkReportRef" :docNo="docNo"/>-->
      </el-dialog>

      <!--排产详情目录弹窗页面-->
      <el-dialog
        title=""
        :visible.sync="schedulingVisible"
        width="60%"
        lock-scroll
        v-dialogDrag
        v-if="schedulingVisible"
        :fullscreen="schedulingDialogFull"
      >
        <el-backtop
          target=".el-card__body .el-dialog__wrapper .el-dialog"
          :right="15"
          :bottom="20"
          :visibility-height="1"
        />
        <el-backtop :bottom="60"></el-backtop>
        <template slot="title">
          <div class="avue-crud__dialog__header">
            <span class="el-dialog__title" style="font-size: 16px">
              <span
                style="
                  display: inline-block;
                  background-color: #3478f5;
                  width: 3px;
                  height: 20px;
                  margin-right: 5px;
                  float: left;
                  margin-top: 2px;
                "
              ></span>
              排产<i class="el-breadcrumb__separator el-icon-arrow-right"></i>
              工单：{{ docNo }}——品号：{{ itemCode }}——预计产量：{{
                planQty
              }}——出货时间：{{ deliveryDate }}——入库时间：{{ storeDate }}
            </span>
          </div>
        </template>
        <div class="el-dialog__body" style="height: 60vh">
          <div style="margin-bottom: 10px">
            <span style="float: left; line-height: 32px">车间产线：</span>
            <div style="float: left">
              <cascaderMultiWorkshopsLineSelect
                ref="selectRef"
                @selection-change="handleSelectionChange"
                :workshops="workshopList"
                :lines="newLineList"
                :docNo="docNo"
                :itemCode="itemCode"
                :scheduleId="scheduleId"
                :checkStrictly="false"
                :multipleFlg="true"
              />
            </div>
            <el-button
              type="primary"
              size="small"
              style="float: left; margin-left: 10px"
              @click="addWorkShopLine"
              >添加</el-button
            >
          </div>
          <div>
            <el-table
              :data="scheduleList"
              border
              style="
                width: 100%;
                height: 55vh;
                margin-top: 20px;
                display: inline-block;
              "
            >
              <el-table-column
                prop="workshopName"
                label="车间"
                show-overflow-tooltip
                align="center"
              ></el-table-column>
              <el-table-column
                prop="productionLineName"
                label="产线"
                show-overflow-tooltip
                align="center"
              ></el-table-column>
              <el-table-column
                prop="scheduleNum"
                label="排产数量"
                show-overflow-tooltip
                align="center"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.scheduleNum"
                    v-if="scope.row.edit"
                    :controls="false"
                    @change="handleScheduleNumChange(scope.row, scope.$index)"
                  ></el-input-number>
                  <span v-else>{{ scope.row.scheduleNum }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="capacity"
                label="标准产量"
                show-overflow-tooltip
                align="center"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.capacity"
                    v-if="scope.row.edit"
                    :controls="false"
                    @change="handleCapacityChange(scope.row, scope.$index)"
                  ></el-input-number>
                  <span v-else>{{ scope.row.capacity }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="startDate"
                label="开工时间"
                show-overflow-tooltip
                align="center"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.startDate"
                    v-if="scope.row.edit"
                    type="date"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    placeholder="请选择开工时间"
                    @change="startDateChange"
                  >
                  </el-date-picker>
                  <span v-else>{{ scope.row.startDate }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="moStatus"
                label="状态"
                show-overflow-tooltip
                align="center"
              >
                <template slot-scope="scope">
                  <span :class="getStatusClass(scope.row.moStatus)">
                    {{ scope.row.moStatus }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.edit">
                    <el-button
                      type="text"
                      size="small"
                      @click="saveRow(scope.$index, scope.row)"
                      >保存</el-button
                    >
                    <el-button
                      type="text"
                      size="small"
                      @click="cancelEdit(scope.$index, scope.row)"
                      >取消</el-button
                    >
                  </div>
                  <div v-else>
                    <el-button
                      type="text"
                      size="small"
                      :disabled="
                        scope.row.moStatus !== '未生产' &&
                        scope.row.moStatus !== '暂停中'
                      "
                      @click="editRow(scope.$index, scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      size="small"
                      @click="delRow(scope.row, scope.$index)"
                      ><i class="el-icon-delete"></i>删除</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>
      <!-- 排产规划 -->
      <el-dialog title="排产规划" :visible.sync="planDialogVisible" width="50%">
        <div>
          <plan ref="planPage" @success="success" :planId="planId" :planDialogVisible="planDialogVisible"></plan>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="planDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="cormBtn">确 定</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  addObj,
  putObj,
  delObj,
} from "@/api/workorder/workordercps";
import { getLineList } from "@/api/pfoc/realityproductlinemain"; //获取产线集合
import { getWorkshopList } from "@/api/pfoc/workshop"; //获取全部车间
import {
  saveWorkSchedulingInfo,
  getWorkSchedulingInfo,
  updateSchedule,
  delSchedule,
} from "@/api/workorder/workscheduling";
import { remote } from "@/api/admin/dict"; //获取内部品类

import { tableOption } from "@/const/crud/workorder/workordercps";
import { mapGetters } from "vuex";
import workOrderReportDetailsPage from "@/views/workorder/workorderreport/index";
import bomDetailsPage from "@/views/workorder/workorderbom/index";
import zzpReportDetailsPage from "@/views/workorder/workinprogressscrapdetails/index.vue";
import wlReportDetailsPage from "@/views/workorder/workordermaterialscrapdetails/index.vue";
import reworkReportDetailsPage from "@/views/workorder/reworkdetails/index.vue";
import cascaderMultiWorkshopsLineSelect from "./cascader-multi-workshops-line-select";
import dr8Page from "@/views/workorder/ilrlview/DR8-LIRL-Histogram.vue";
import genPage from "@/views/workorder/ilrlview/GEN1.5-ILRL-Histogram.vue";
import sr8Page from "@/views/workorder/ilrlview/SR8-LIRL-Histogram.vue";
import plan from "./plan.vue";

export default {
  name: "workordercps",
  components: {
    reworkReportDetailsPage,
    wlReportDetailsPage,
    zzpReportDetailsPage,
    //报工详情页面
    workOrderReportDetailsPage,
    //物料详情页面
    bomDetailsPage,
    //车间产线级联选择器
    cascaderMultiWorkshopsLineSelect,
    dr8Page,
    genPage,
    sr8Page,
  },
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 30, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      lineList: [], //产线集合
      newLineList: [], //过滤后的产线集合
      workshopList: [], //车间数据集合
      scheduleList: [], //排单集合
      handleSelect: [], //接收车间选择结果点击确认时清空
      reportDialogVisible: false, //报工详情页面开关
      reportDialogFull: true, //报工详情页面弹窗缩放开关（默认放大）
      schedulingVisible: false, //排产详情页面开关
      schedulingDialogFull: false, //排产详情页面弹窗缩放开关（默认放大）
      bomDialogVisible: false, //物料详情页面开关
      bomDialogFull: true, //物料详情页面弹窗缩放开关（默认放大）
      title: null,
      flg: null,
      docNo: null, //工单号
      itemCode: null, //品号
      storeDate: null, //入库时间
      deliveryDate: null, //出库时间
      planQty: null, //预计产量
      scheduleId: null, //工单表ID
      originalRows: {}, // 用于存储原始数据的备份
      dateFlg: false, //判断开工时间是否修改如果修改则不自动计算
      internalCategory: [],
      planDialogVisible: false,
      planId: "",
    };
  },
  components: {
    plan, // 引入排产组件
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.workorder_workordercps_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.workorder_workordercps_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.workorder_workordercps_edit,
          false
        ),
      };
    },
  },
  created() {
    //获取内部品类
    this.getInternalCategoryData();
    //获取车间集合
    this.getWorkshopListData();
    //获取产线集合
    this.getLineListData();
  },
  methods: {
    cormBtn() {
      this.$refs.planPage.handleSubmit();
    },
    success() {
      this.planDialogVisible = false;
      this.getList(this.page);
    },
    workOrderPlan(row) {
      this.planId = row.id;
      this.planDialogVisible = true;
    },
    // 列表查询
    getList(page, params) {
      this.tableLoading = true;
      console.log(this.searchForm);
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 删除
    handleDel: function (row, index) {
      this.$confirm("是否确认删除工单" + row.docNo, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delObj(row.id);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    // 更新
    handleUpdate: function (row, index, done, loading) {
      row.deliveryDate = this.deliveryDate;
      putObj(row)
        .then((data) => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    // 保存
    handleSave: function (row, done, loading) {
      row.deliveryDate = this.deliveryDate;
      addObj(row)
        .then((data) => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page);
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile(
        "/workorder/workordercps/export",
        this.searchForm,
        "workordercps.xlsx"
      );
    },
    //获取产线集合
    getLineListData() {
      getLineList().then((response) => {
        this.lineList = response.data.data;
      });
    },
    /**获取车间集合*/
    getWorkshopListData() {
      getWorkshopList().then((response) => {
        this.workshopList = response.data.data;
      });
    },
    //出货时间选择
    deliveryDateChange(row) {
      // 将出货时间转换为 Date 对象
      const deliveryDateObj = new Date(this.deliveryDate);
      // 计算预计提前入库时间（出货时间往前推两天）
      let estimatedInboundDate = new Date(deliveryDateObj);
      estimatedInboundDate.setDate(estimatedInboundDate.getDate() - 2);
      //estimatedInboundDate格式化成YYYY-MM-DD格式
      let formattedDate = estimatedInboundDate.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      });
      //将estimatedInboundDate中的/转成-
      formattedDate = formattedDate.replace(/\//g, "-");
      if (this.validatenull(row)) {
        this.$set(this.$refs["crud"].tableForm, "storeDate", formattedDate);
      } else {
        row.storeDate = formattedDate;
        row.deliveryDate = this.deliveryDate;
      }
    },
    /**排产*/
    openScheduling(row) {
      this.docNo = row.docNo; //工单号
      this.itemCode = row.itemCode; //品号
      this.storeDate = row.storeDate; //入库时间
      this.deliveryDate = row.deliveryDate; //出库时间
      this.planQty = row.planQty; // 预计产量
      //根据当前数据查询当前符合当前品号的产线数据
      var articleNumber = row.itemCode; //品号
      this.originalRows = {};
      var newLineList = []; //新产线集合
      this.lineList.forEach((item) => {
        var bindArticleNumber = item.bindArticleNumber; //产线已绑定品号字符串
        if (bindArticleNumber.includes(articleNumber)) {
          //判断当前产线绑定的品号中是否包含当前行编辑的工单品号 true包含；false不包含
          newLineList.push(item); //包含则加入新的产线集合
        }
      });
      this.newLineList = newLineList;
      this.schedulingVisible = true;
      // 初始化排产列表
      this.scheduleList = [];
      this.scheduleId = row.id; //工单表ID
      //查询当前工单的排产信息
      getWorkSchedulingInfo(this.docNo).then((response) => {
        this.scheduleList = response.data.data;
      });
    },
    //车间产线选择回调
    handleSelectionChange(selectedData) {
      this.handleSelect = selectedData;
    },
    //产线排产添加车间产线
    addWorkShopLine() {
      let duplicateItems = []; // 用于记录重复的对象及其信息
      //记录不重复的
      let newScheduleList = [];
      // 遍历 this.handleSelect 集合中的每个对象
      this.handleSelect.forEach((selectedItem) => {
        // 检查是否有重复的对象
        const isDuplicate = this.scheduleList.some(
          (item) => item.productionLineId === selectedItem.productionLineId
        );
        if (isDuplicate) {
          // 记录重复的对象及其信息
          duplicateItems.push({
            workshopName: selectedItem.workshopName,
            productionLineName: selectedItem.productionLineName,
          });
        } else {
          // 将选中的数据添加到 scheduleList 中
          newScheduleList.push({ ...selectedItem });
        }
      });

      var obj = {
        workSchedulingList: newScheduleList,
        workOrderId: this.scheduleId,
      };
      //保存排产添加信息
      saveWorkSchedulingInfo(obj).then((response) => {
        this.$message.success("排产添加成功");
        this.scheduleList = response.data.data;
        // 如果有重复的对象，提示用户具体的重复信息
        if (duplicateItems.length > 0) {
          const duplicateInfo = duplicateItems
            .map(
              (item) =>
                `车间: ${item.workshopName}, 产线: ${item.productionLineName}`
            )
            .join("; ");
          this.$message.warning(
            `部分选择已存在，请勿重复添加！重复项包括：${duplicateInfo}`
          );
        }
        //刷新父页面
        this.getList(this.page);
        // 清空 this.handleSelect
        this.handleSelect = [];
        // 清空子组件的选择
        this.$refs.selectRef.clearSelection();
      });
    },
    //排产弹窗页面标准产量输入框改变事件
    handleCapacityChange(row) {
      if (
        !this.validatenull(row.capacity) &&
        !this.validatenull(this.storeDate) &&
        !this.validatenull(row.scheduleNum)
      ) {
        const deliveryDateObj = new Date(this.storeDate);
        const currentDate = new Date(deliveryDateObj.getTime());
        row.startDate = this.calculateStartDate(
          currentDate,
          row.capacity,
          row.scheduleNum
        );
      }
    },
    //排产弹窗页面排产数量输入框改变事件
    handleScheduleNumChange(row) {
      if (this.planQty) {
        // 计算剩余可排产数量，不包含当前输入的排产数量
        const totalScheduled = this.scheduleList.reduce((total, item) => {
          if (item !== row) {
            return total + (item.scheduleNum || 0);
          }
          return total;
        }, 0);
        const remainingCapacity = this.planQty - totalScheduled;

        // 如果输入的排产数量大于剩余可排产数量，直接将输入的排产数量设置为剩余可排产数量
        if (row.scheduleNum > remainingCapacity) {
          row.scheduleNum = remainingCapacity;
          this.$message({
            message: `输入的排产数量已自动调整为剩余可排产数量: ${remainingCapacity}`,
            type: "info",
          });
        }
      }
      //剩余数量=排产数量-已完成数量（如果已完成数量为空则剩余数量等于排产数量）
      row.remainingQty = row.scheduleNum - (row.completedQty || 0);
      if (
        !this.dateFlg &&
        !this.validatenull(row.capacity) &&
        !this.validatenull(this.storeDate) &&
        !this.validatenull(row.scheduleNum)
      ) {
        const deliveryDateObj = new Date(this.storeDate);
        const currentDate = new Date(deliveryDateObj.getTime());
        row.startDate = this.calculateStartDate(
          currentDate,
          row.capacity,
          row.scheduleNum
        );
      }
    },
    // 计算每条产线的开始时间
    calculateStartDate(storeDate, capacity, scheduleNum) {
      if (scheduleNum !== 0) {
        const storeDateObj = new Date(storeDate);
        const requiredDays = Math.ceil(scheduleNum / capacity);
        const startDate = new Date(storeDateObj);
        startDate.setDate(startDate.getDate() - requiredDays + 1); // 加1是因为当天也算一天
        return startDate.toISOString().split("T")[0]; // 转换为 YYYY-MM-DD 格式
      } else {
        return null;
      }
    },
    editRow(index, row) {
      // 备份原始数据
      this.$set(this.originalRows, row.id, { ...row });
      this.dateFlg = false;
      // 动态添加 edit 属性
      this.$set(row, "edit", true);
    },

    startDateChange() {
      this.dateFlg = true;
    },
    saveRow(index, row) {
      this.handleScheduleNumChange(row);
      //剩余数量=排产数量-已完成数量（如果已完成数量为空则剩余数量等于排产数量）
      row.remainingQty = row.scheduleNum - (row.completedQty || 0);
      //如果日完成量和已完成量为空则默认为0
      if (this.validatenull(row.dailyCompleteQty)) {
        row.dailyCompleteQty = 0;
      }
      if (this.validatenull(row.completeQty)) {
        row.completeQty = 0;
      }
      // 这里可以添加保存逻辑，例如更新数据源
      updateSchedule(row).then((response) => {
        this.$message.success("修改成功");
        this.getList(this.page);
        this.scheduleList = response.data.data;
        this.$set(row, "edit", false);
      });
    },
    cancelEdit(index, row) {
      // 从备份对象中恢复原始数据
      Object.assign(row, this.originalRows[row.id]);
      // 移除备份对象中的数据
      this.$delete(this.originalRows, row.id);
      // 取消编辑，恢复原始数据
      this.$set(row, "edit", false);
    },
    delRow(row, index) {
      // 删除操作
      this.$confirm(
        "是否确认删除" + row.productionLineName + "排产？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delSchedule(row.id);
        })
        .then((response) => {
          this.$message.success("删除成功");
          this.getList(this.page);
          this.scheduleList = response.data.data;
        });
    },
    //排产信息生产状态颜色
    getStatusClass(status) {
      switch (status) {
        case "未生产":
          return "status-未生产";
        case "生产中":
          return "status-生产中";
        case "暂停中":
          return "status-暂停中";
        case "已完工":
          return "status-已完工";
        default:
          return "";
      }
    },
    //报工详情
    workOrderReportDetails(row) {
      this.reportDialogVisible = true;
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      this.title = "工单报工详情";
      this.flg = "gd";
      this.$nextTick(() => {
        //调用报工详情查询方法
        this.$refs.reportRef.refreshChange();
      });
    },
    //插回损直方图
    clrlHistogram(row, index) {
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      let flg = false;
      let flgTile = null;
      for (let i = 0; i < this.internalCategory.length; i++) {
        if (this.internalCategory[i].itemCode.includes(this.itemCode)) {
          if (this.internalCategory[i].label === "GEN1.5") {
            flg = true;
            flgTile = "GEN1.5";
            this.flg = "gen";
            this.title = "GEN1.5插回损直方图";
          }
          if (this.internalCategory[i].label === "DR8") {
            flg = true;
            flgTile = "DR8";
            this.flg = "dr8";
            this.title = "DR8插回损直方图";
          }
          if (this.internalCategory[i].label === "SR8") {
            flg = true;
            flgTile = "SR8";
            this.flg = "sr8";
            this.title = "SR8插回损直方图";
          }
        }
      }
      if (!flg) {
        this.$message({
          message:
            "该工单品号不在GEN1.5、DR8、SR8三种内部品类中的任意一种，暂无插回损直方图",
          type: "info",
        });
        return;
      }
      this.reportDialogVisible = true;
      this.$nextTick(() => {
        if (flgTile === "GEN1.5") {
          this.$refs.genRef.refreshChange();
        }
        if (flgTile === "DR8") {
          this.$refs.dr8Ref.refreshChange();
        }
        if (flgTile === "SR8") {
          this.$refs.sr8Ref.refreshChange();
        }
      });
    },
    //获取内部品类
    getInternalCategoryData() {
      remote("product_line").then((response) => {
        this.internalCategory = response.data.data;
      });
    },
    //在制品报工详情
    zzpReportDetails(row, index) {
      this.reportDialogVisible = true;
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      this.title = "在制品不良明细";
      this.flg = "zzp";
      this.$nextTick(() => {
        //调用报工详情查询方法
        this.$refs.zzpReportRef.refreshChange();
      });
    },
    //物料报工详情
    wlReportDetails(row, index) {
      this.reportDialogVisible = true;
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      this.title = "物料不良明细";
      this.flg = "wl";
      this.$nextTick(() => {
        //调用报工详情查询方法
        this.$refs.wlReportRef.refreshChange();
      });
    },
    //返工详情
    reworkReportDetails(row, index) {
      this.reportDialogVisible = true;
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      this.title = "返工原因明细";
      this.flg = "rework";
      this.$nextTick(() => {
        //调用报工详情查询方法
        this.$refs.reworkReportRef.refreshChange();
      });
    },
    //工单详情
    workOrderDetails(row) {
      this.$router.push({
        path: "/workorder/workorderproductionreport/index",
        query: {
          docNo: row.docNo,
        },
      });
    },
    //工单物料详情（BOM）
    workOrderBomDetails(row) {
      this.bomDialogVisible = true;
      this.docNo = row.docNo;
      this.itemCode = row.itemCode;
      this.$nextTick(() => {
        //调用物料详情
        this.$refs.workOrderBomRef.refreshChange();
      });
    },

    //补单
    supplementaryOrder(row) {},
    /*   //行编辑
    rowCell (row, index) {
       //根据当前数据查询当前符合当前品号的产线数据
       var articleNumber = row.itemCode;//品号
       var column = this.findObject(this.tableOption.column,'lineId');
       var newLineList=[];//新产线集合
       this.lineList.forEach(item =>{
         var bindArticleNumber = item.bindArticleNumber;//产线已绑定品号字符串
         if(bindArticleNumber.includes(articleNumber)){//判断当前产线绑定的品号中是否包含当前行编辑的工单品号 true包含；false不包含
           newLineList.push(item);//包含则加入新的产线集合
         }
       })
       column.dicData= newLineList;
       this.$refs.crud.rowCell(row, index)
    },*/
  },
};
</script>

<style scoped>
/* 隐藏 Element UI 日期选择器的前后图标 */
/deep/.el-date-editor .el-range-separator + .el-popper {
  display: none;
}
/deep/.status-未生产 {
  color: red;
}

/deep/.status-生产中 {
  color: green;
}

/deep/.status-暂停中 {
  color: orange;
}

/deep/.status-已完工 {
  color: rgba(68, 68, 68, 0.73);
}
</style>
